package com.shopx.auth.service.impl;


import com.shopx.auth.bean.SysRole;
import com.shopx.auth.bean.SysRoleUrl;
import com.shopx.auth.bean.SysUserRole;
import com.shopx.auth.dao.db1.SysRoleDao;
import com.shopx.auth.dao.db1.SysRoleUrlDao;
import com.shopx.auth.dao.db1.SysUserRoleDao;
import com.shopx.auth.model.SysRoleModel;
import com.shopx.auth.model.SysRoleUrlModel;
import com.shopx.auth.model.SysUserModel;
import com.shopx.auth.service.ISysRoleService;
import com.shopx.base.constants.ResultCodeEnum;
import com.shopx.base.exception.OriginException;
import com.shopx.base.exception.ShopxException;
import com.shopx.base.service.ISysSeqService;
import com.shopx.cmm.DTO.PageDTO;
import com.shopx.core.common.CommonConstant;
import com.shopx.core.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @author lituo
 * @className: SysConfigServiceImpl
 * @description: 角色服务
 * @date 2021/12/5 11:24 AM
 */
@Service
@Slf4j
public class SysRoleServiceImpl extends BaseAuthService implements ISysRoleService {

  @Resource
  private SysRoleDao sysRoleDao;

  @Resource
  private SysRoleUrlDao sysRoleUrlDao;

  @Resource
  private SysUserRoleDao sysUserRoleDao;

  @Resource
  private ISysSeqService sysSeqService;

  @Resource
  TransactionTemplate transactionTemplate1;

  @Override
  public SysRoleModel selectByPrimaryKey(SysRole sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    SysRoleModel sr =  sysRoleDao.selectByPrimaryKey(sysRole);
    //查询绑定的菜单
    SysRoleUrlModel sysRoleUrl = new SysRoleUrlModel();
    sysRoleUrl.setRoleCode(sr.getRoleCode());
    sysRoleUrl.setCpId(super.getUserCpId());
    List<SysRoleUrlModel> list = sysRoleUrlDao.selectList(sysRoleUrl);
    String urlIds = "";
    for(SysRoleUrlModel model:list){
      urlIds+=model.getUrlId()+",";
    }
    if(urlIds.split(",").length>1){
      urlIds = urlIds.substring(0,urlIds.length()-1);
    }
    sr.setUrlIds(urlIds);
    return sr;
  }


  @Override
  public SysRole selectByRoleCode(SysRole sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    sysRole.setCpId(super.getUserCpId());
    return sysRoleDao.selectByCode(sysRole);
  }


  @Override
  @Transactional(value = "db1", rollbackFor = Exception.class)
  public int insertSelective(SysRoleModel sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    String id = sysSeqService.getTabSeq("SysRole", 6, null);
    sysRole.setRoleId(id);
    sysRole.setCpId(super.getUserCpId());
    sysRole.setDefaultFlag(CommonConstant.DefaultFlag.N);
    sysRole.setState(CommonConstant.State.EFFECTIVE);
    int result = sysRoleDao.insertSelective(sysRole);
    if (result != 1) {
      throw new ShopxException(ResultCodeEnum.DB_ERROR);
    }
    if (!StringUtil.isEmpty(sysRole.getUrlIds())) {
      this.insertRoleUrl(sysRole.getUrlIds(), sysRole.getRoleCode());
    }
    return result;
  }

  /**
   * @return void
   * @Author lituo
   * @Description //新增角色菜单
   * @Date 2021/1/9
   * @Param [urlIds, roleCode]
   **/
  private void insertRoleUrl(String urlIds, String roleCode) {
    if (StringUtil.isEmpty(urlIds)) {
      throw new OriginException("99999", "请至少绑定一个菜单");
    }
    int result = 0;
    String[] arry = urlIds.split(",");
    if ("".equals(urlIds.trim())) {
    } else {
      arry = StringUtil.arrayUnique(arry);
      SysRoleUrl roleUrl = new SysRoleUrl();
      for (String urlId : arry) {
        if (!"0".equals(urlId) && !StringUtil.isEmpty(urlId)) {
          roleUrl.setRoleCode(roleCode);
          roleUrl.setUrlId(urlId);
          roleUrl.setCpId(super.getUserCpId());
          roleUrl.setDefaultFlag(CommonConstant.DefaultFlag.N);
          result = sysRoleUrlDao.insertSelective(roleUrl);
          if (result != 1) {
            throw new ShopxException(ResultCodeEnum.DB_ERROR);
          }
        }
      }
    }
  }

  @Override
  @Transactional(value = "db1", rollbackFor = Exception.class)
  public void updateByPrimaryKeySelective(SysRoleModel sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    int result = 0;
    SysRoleModel model = this.selectByPrimaryKey(sysRole);
    if (!CommonConstant.DefaultFlag.Y.equals(model.getDefaultFlag())) {
      //默认角色不允许编辑角色表信息
      sysRole.setCpId(super.getUserCpId());
      result = sysRoleDao.updateByPrimaryKeySelective(sysRole);
      if (result != 1) {
        throw new ShopxException(ResultCodeEnum.DB_ERROR);
      }
    }
    String cpId = super.getUserCpId();
    SysRoleUrlModel roleUrl = new SysRoleUrlModel();
    roleUrl.setRoleCode(sysRole.getRoleCode());
    roleUrl.setCpId(cpId);
    //角色当前绑定所有的菜单
    List<SysRoleUrlModel> list = sysRoleUrlDao.selectList(roleUrl);
    //本轮编辑菜单
    String urlIds2 = sysRole.getUrlIds();
    if(StringUtil.isEmpty(urlIds2)){
//      throw new OriginException("请选择编辑的菜单");
      //清除所有菜单
      for(SysRoleUrlModel srum:list){
        SysRoleUrl sru = new SysRoleUrl();
        sru.setUrlId(srum.getUrlId());
        sru.setRoleCode(srum.getRoleCode());
        sru.setCpId(srum.getCpId());
        result = sysRoleUrlDao.deleteByPrimaryKey(sru);
        if(result!=1){
          throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
      }
    }else{
      //清除重复项
      String urlIds = "";
      for(String urlId:urlIds2.split(",")){
        if(StringUtil.isEmpty(urlId)){
          continue;
        }
        //有问题 TODO
        if(this.repeatCheck(urlId,urlIds)){
          continue;
        }
        urlIds+=urlId+",";
      }

      List<String> addUrlList = new ArrayList<String>();
      List<String> delUrlList = new ArrayList<String>();
      //查询新增的菜单
      for (String urlId : urlIds.split(",")) {
        boolean addFlag = true;
        if (StringUtil.isEmpty(urlId)) {
          continue;
        }
        for (SysRoleUrlModel sruModel : list) {
          if (urlId.equals(sruModel.getUrlId())) {
            //存在，跳出
            addFlag = false;
            break;
          }
        }
        if (addFlag) {
          addUrlList.add(urlId);
        }
      }

      //新增记录
      for(String urlId:addUrlList){
        SysRoleUrl sysRoleUrl = new SysRoleUrl();
        sysRoleUrl.setUrlId(urlId);
        sysRoleUrl.setCpId(cpId);
        sysRoleUrl.setRoleCode(sysRole.getRoleCode());
//      sysRoleUrl.setCreateUserId();
        sysRoleUrl.setDefaultFlag(CommonConstant.DefaultFlag.N);
        result = sysRoleUrlDao.insertSelective(sysRoleUrl);
        if(result!=1){
          throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
      }


      List<SysRoleUrlModel> list2 = sysRoleUrlDao.selectList(roleUrl);

      //查询删除的菜单，如果是默认菜单则不处理，否则删除
      for (SysRoleUrlModel sruModel : list2) {
        boolean delFlag = true;
        for (String urlId : urlIds.split(",")) {
          if (StringUtil.isEmpty(urlId)) {
            continue;
          }
          if (urlId.equals(sruModel.getUrlId())) {
            //存在，跳出
            delFlag = false;
            break;
          }
        }
        if(CommonConstant.DefaultFlag.Y.equals(sruModel.getDefaultFlag())){
          continue;
        }
        if(delFlag){
          delUrlList.add(sruModel.getUrlId());
        }
      }

      //删除记录
      for(String urlId:delUrlList){
        SysRoleUrl sysRoleUrl = new SysRoleUrl();
        sysRoleUrl.setUrlId(urlId);
        sysRoleUrl.setCpId(cpId);
        sysRoleUrl.setRoleCode(sysRole.getRoleCode());
        result = sysRoleUrlDao.deleteByPrimaryKey(sysRoleUrl);
        if(result!=1){
          throw new ShopxException(ResultCodeEnum.DB_ERROR);
        }
      }
    }
  }

  /**
   * @auth lituo
   * @date 2022/8/2
   * @param urlId
   * @param urlIds
   * @desc  验证是否重复菜单配置
   * @return
   **/
  private boolean repeatCheck(String urlId,String urlIds){
    boolean repeatFlag = false;
    for(String uId:urlIds.split(",")){
      if(urlId.equals(uId)){
        repeatFlag = true;
        break;
      }
    }
    return repeatFlag;
  }

  @Override
  @Transactional(value = "db1", rollbackFor = Exception.class)
  public void deleteBatch(List<SysRole> list) throws ShopxException{
    //删除角色对应菜单
    for(SysRole sr:list){
      sr.setCpId(super.getUserCpId());
      SysRoleModel model = this.selectByPrimaryKey(sr);
      if (model == null) {
        throw new OriginException("99999", "角色不存在");
      }
      if (CommonConstant.DefaultFlag.Y.equals(model.getDefaultFlag())) {
        throw new OriginException("默认角色不允许删除");
      }
      int result = sysRoleDao.deleteByPrimaryKey(sr);
      if (result != 1) {
        throw new ShopxException(ResultCodeEnum.DB_ERROR);
      }
      SysRoleUrl roleUrl = new SysRoleUrl();
      roleUrl.setRoleCode(model.getRoleCode());
      roleUrl.setCpId(super.getUserCpId());
      sysRoleUrlDao.deleteByRoleCode(roleUrl);

      SysUserRole sur = new SysUserRole();
      sur.setRoleCode(model.getRoleCode());
      sur.setCpId(super.getUserCpId());
      sysUserRoleDao.deleteByRoleCode(sur);
    }
  }

  @Override
  @Transactional(value = "db1", rollbackFor = Exception.class)
  public int deleteByPrimaryKey(SysRole sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    SysRoleModel model = this.selectByPrimaryKey(sysRole);
    if (model == null) {
      throw new OriginException("99999", "角色不存在");
    }
    if (CommonConstant.DefaultFlag.Y.equals(model.getDefaultFlag())) {
      throw new OriginException("默认角色不允许删除");
    }
    sysRole.setCpId(super.getUserCpId());
    int result = sysRoleDao.deleteByPrimaryKey(sysRole);
    if (result != 1) {
      throw new ShopxException(ResultCodeEnum.DB_ERROR);
    }
    SysRoleUrl roleUrl = new SysRoleUrl();
    roleUrl.setRoleCode(model.getRoleCode());
    roleUrl.setCpId(super.getUserCpId());
    sysRoleUrlDao.deleteByRoleCode(roleUrl);
    return result;
  }

  private int selectCount(SysRoleModel sysRole) throws ShopxException {
    return sysRoleDao.selectCount(sysRole);
  }

  private List<SysRoleModel> selectList(SysRoleModel sysRole) throws ShopxException {
    List<SysRoleModel> list = sysRoleDao.selectList(sysRole);
    return list;
  }

  @Override
  public List<SysRoleModel> queryList(SysRoleModel sysRoleModel) {
    if (sysRoleModel == null) {
      sysRoleModel = new SysRoleModel();
    }
    sysRoleModel.setCpId(super.getUserCpId());
    sysRoleModel.setState(CommonConstant.State.EFFECTIVE);
    String[] excloudRoleCode = new String[]{CommonConstant.RoleCode.ENT_ADMIN};
    sysRoleModel.setExcloudRoleCode(excloudRoleCode);
    return sysRoleDao.selectList(sysRoleModel);
  }


  @Override
  public List<SysRoleModel> queryEditList(SysRoleModel sysRole) throws ShopxException {
    //如果是店长，则只能新增店铺用户，平台管理员则可以新增所有
    String roleCodes = super.getLoginUserRoleCodes();
    for(String roleCode:roleCodes.split(",")){
      if(CommonConstant.RoleCode.SHOP_OWNER.equals(roleCode)){
        sysRole.setRoleTypes(CommonConstant.RoleType.STORE);
      }
    }
    String roleTypes = sysRole.getRoleTypes();
    if(!StringUtil.isEmpty(roleTypes)){
      sysRole.setRoleType(null);
      String[] roleTypeChk = new String[roleTypes.split(",").length];
      int i=0;
      for(String roleType:roleTypes.split(",")){
        if(StringUtil.isEmpty(roleType)){
          continue;
        }
        roleTypeChk[i] = roleType;
        i++;
      }
      sysRole.setRoleTypeChk(roleTypeChk);
    }
    return this.queryList(sysRole);
  }

  @Override
  public PageDTO<SysRoleModel> getListPage(SysRoleModel sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    PageDTO<SysRoleModel> pageDTO = new PageDTO<SysRoleModel>();
    sysRole.setCpId(super.getUserCpId());
    pageDTO.setiTotalDisplayRecords(selectCount(sysRole));
    //企业管理员看看到所有的
//    SysUserModel sum = super.getLoginUserInfo();
//    String adminFlag = sum.getCpAdminFlag();
//    if(CommonConstant.CpAdminFlag.YES.equals(adminFlag)){
//    }else{
//      String[] excloudRoleCode = new String[]{CommonConstant.RoleCode.ENT_ADMIN};
//      sysRole.setExcloudRoleCode(excloudRoleCode);
//    }
    pageDTO.setData(selectList(sysRole));
    return pageDTO;
  }



  @Override
  public String queryMatchUrl(SysRole sysRole) throws ShopxException {
    if (sysRole == null) {
      throw new ShopxException(ResultCodeEnum.PAR_NULL);
    }
    SysRole SysRoleRecord = sysRoleDao.selectByPrimaryKey(sysRole);
    if (SysRoleRecord == null) {
      throw new OriginException("99999", "角色不存在");
    }
    String roleCode = SysRoleRecord.getRoleCode();
    SysRoleUrlModel roleUrl = new SysRoleUrlModel();
    roleUrl.setRoleCode(roleCode);
    roleUrl.setCpId(super.getUserCpId());
    List<SysRoleUrlModel> list = sysRoleUrlDao.selectList(roleUrl);
    if (list.size() == 0) {
      return "";
    }
    String urlIds = "";
    for (SysRoleUrlModel resUrlModel : list) {
      urlIds += resUrlModel.getUrlId() + ",";
    }
    return urlIds.substring(0, urlIds.length() - 1);
  }
}




